import { GameEvent, SysOrder } from "../../GameDef";
import { IECSFilter } from "../../lib/kgame/ecs/ECSFilter";
import { ECSSys } from "../../lib/kgame/ecs/ECSSys";
import { FoodCmp } from "../cmp/FoodCmp";
import { SnakeHeadCmp } from "../cmp/SnakeHeadCmp";
import { FoodFactory } from "../factory/FoodFactory";
import { WorldMgr } from "../scmp/WorldMgr";

const eatenFoods: kp_entity_eatenFood[] = [];

/**
 * 食物系统
 */
export class FoodSys extends ECSSys {

    get updateOrder(): number {
        return SysOrder.food;
    }

    get ifilter(): IECSFilter {
        return { includeOne: [FoodCmp] };
    }

    onUpdate(): void {
        const world = this.scene.getCmp(WorldMgr);
        const { rand } = this.scene;

        let count = world.foodMax - this.getCmps(FoodCmp).size;
        while (--count >= 0) {

            const score = rand.rand() < 0.01 ? rand.range(100, 200) : rand.range(5, 10);
            const spawnPos = world.getRandPos(FoodCmp.getSize(score));
            FoodFactory.createFood(this.scene, spawnPos, score);
        }
    }

    onLateUpdate(): void {
        eatenFoods.length = 0;
        this.getCmps(FoodCmp).forEach(food => {
            if (food.collider.collidersSelf.length > 0) {
                //被吃了
                const head = food.collider.collidersSelf[0].getCmp(SnakeHeadCmp);
                head.score += food.score;
                eatenFoods.push({
                    id: food.entityId,
                    eaterId: head.entityId
                });
                food.entity.removeSelf();
            } else if (food.lifeTime > -1) {
                food.lifeTime -= this.scene.dt;
                if (food.lifeTime <= 0) {
                    food.entity.removeSelf();
                }
            }
        });

        if (eatenFoods.length > 0) {
            this.scene.send(GameEvent.foodEaten, eatenFoods);
        }
    }

}

declare global {
    interface ECSEventData {
        [GameEvent.foodEaten]: readonly kp_entity_eatenFood[]
    }
}